<template>
	<view>
		<el-divider content-position="left">
			<span class="h1">用户管理</span>
		</el-divider>
		<h1>用户编辑</h1>
		<br>
		<div>
			<el-button type="primary" :dark="isDark" plain @click="addData">+ 新增</el-button>
			<el-button type="danger" :dark="isDark" plain @click="batchDel">- 批量删除</el-button>
			<p style="color: grey;">！！!新增用户密码初始值为123456</p>
		</div>
		<br>
		<div>
			<el-input v-model="query.username" placeholder="用户名" style="width: 200px"></el-input>
			<el-input v-model="query.phone" placeholder="手机号" style="width: 200px"></el-input>
			<el-button type="primary" :dark="isDark" plain @click="search">查询</el-button>
			<el-button type="primary" :dark="isDark" plain @click="reset">重置</el-button>
		</div>
		<br>
		<!-- element-plus表格 -->
		<el-table ref="tableRef" :data="formData" style="width: 100%" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" fixed="left" />
			<el-table-column prop="username" label="用户名" />
			<el-table-column prop="name" label="昵称" />
			<el-table-column prop="email" label="邮箱" />
			<el-table-column prop="phone" label="手机号" />
			<el-table-column label="性别">
				<template #default="scope">
					<span v-if="scope.row.gender == 1">男</span>
					<span v-else-if="scope.row.gender == 0">女</span>
				</template>
			</el-table-column>
			<el-table-column label="状态" prop="status">
				<template #default="scope">
					<el-switch v-model="scope.row.status" :active-value=1 :inactive-value=0  disabled></el-switch>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="180" fixed="right">
				<template #default="{ row }">
					<el-button type="primary" size="small" @click="edit(row)">编辑
					</el-button>
					<el-popconfirm title="确定要删除吗?" @confirm="delData(row)" confirm-button-text="是"
						cancel-button-text="否">
						<template #reference>
							<el-button type="danger" size="small">删除</el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
		<br>

		<!-- element-plus分页 -->
		<el-pagination v-model:current-page="query.current" :page-size="query.pageSize" layout="total,  prev, pager, next, jumper"
			:total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

		<!-- 新增/编辑表单 -->
		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
			<el-form :model="formDTO" ref="vForm" :rules="rules" label-position="right" label-width="80px" size="medium"
				@submit.prevent>
				<el-form-item label="用户id" prop="userId">
					<el-input v-model="formDTO.userId" type="text" clearable :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="用户名" prop="username">
					<el-input v-model="formDTO.username" type="text" clearable></el-input>
				</el-form-item>
				<el-form-item label="昵称" prop="name">
					<el-input v-model="formDTO.name" type="text" clearable></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="formDTO.email" type="text" clearable></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="formDTO.phone" type="text" clearable></el-input>
				</el-form-item>
				<el-form-item label="性别:" prop="gender">
					<el-select-v2 v-model="formDTO.gender" :options="genderIdCount" />
				</el-form-item>
				<el-form-item label="状态" prop="status" class="label-right-align">
					<el-switch v-model="formDTO.status" :active-value=1 :inactive-value=0></el-switch>
				</el-form-item>


				<el-form-item>
					<el-button type="primary" @click="submit">提交</el-button>
					<el-button @click="dialogVisible = false">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		setDevtoolsHook,
		onMounted
	} from "vue";
	import {
		admin
	} from '@/api'
	import { ElNotification } from 'element-plus'
	//分页数据
	const page = ref(1);
	const pageSize = ref(10);
	const total = ref(0);
	const list = ref([]);
	//删除列表
	const delList = ref([]);
	const tableRef = ref();
	//弹出层
	const dialogVisible = ref(false);
	const dialogTitle = ref("");
	const vForm = ref(null);

	//表单数据
	const formData = ref([]);

	//验证规则
	const rules = ref({
		postId: [{
			pattern: /^[-]?\d+(\.\d+)?$/,
			trigger: ["blur", "change"],
			message: "",
		}, ],
		userId: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		categoryId: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		username: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		title: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		content: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		summary: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		image: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		createTime: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		updateTime: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		views: [{
			required: true,
			message: "字段值不可为空",
		}, ],
		status: [{
			required: true,
			message: "字段值不可为空",
		}, ],
	});

	//提交表单结构
	const formDTO = ref({
		userId: "",
		name: "",
		username: "",
		password: "",
		email: "",
		phone: "",
		gender: "",
		status: "",
		role: "",
	});
	//表单选择数字转换成字符
	const genderIdCount = Array.from({
		length: 2
	}).map((_, idx) => {
		const labels = [
			'女',
			'男'
		];
		const label = labels[idx % labels.length]; // 使用模运算符确保索引在数组范围内
		return {
			value: `${idx + 0}`,
			label: label
		};
	});

	const statusCount = Array.from({
		length: 2
	}).map((_, idx) => {
		const labels = [
			'删除',
			'启用'

		];
		const label = labels[idx % labels.length]; // 使用模运算符确保索引在数组范围内
		return {
			value: `${idx + 0}`,
			label: label
		};
	});
	//查询分页参数
	const query = ref({
		pageSize: 10,
		current: 1,
		role: "regular"
	});


	/**
	 * 数据处理-------------------------
	 */

	/**
	 * 编辑
	 */
	const edit = (row) => {
		dialogTitle.value = "编辑表单";
		dialogVisible.value = true;
		if (vForm.value) {
			vForm.value.resetFields(); // 确保调用resetFields来重置验证
		}
		// 深拷贝form
		for (let key in formDTO.value) {
			formDTO.value[key] = row[key];
		}
		console.log(row);
	};

	/**
	 * 删除
	 */
	 const delData = (row) => {
		console.log(row.userId);
		del([row.userId])
	};

	/**
	 * 批量删除
	 */
	const batchDel = () => {
		del(delList.value);
		console.log(delList.value);
		// 清空选中列表
		tableRef.value.clearSelection();
	};

	/**
	 * 查询
	 */
	const search = () => {
		get()
		console.log(query.value);
	};

	/**
	 * 重置
	 */
	const reset = () => {
		query.value = {
			pageSize: 10,
			current: 1,
			categoryId: "",
			title: "",
			role: "regular"
		};
		get()
	};

	/**
	 * 新增
	 */
	const addData = () => {
		dialogTitle.value = "新增表单";
		dialogVisible.value = true;
		formDTO.value = {};
		// 重置表单验证状态
		if (vForm.value) {
			vForm.value.resetFields();
		}
	};

	/**
	 * 提交
	 */
	const submit = () => {
		dialogVisible.value = false;
		if (dialogTitle.value === '编辑表单') {
			//调用修改接口
			put(formDTO.value);

		} else {
			//调用添加接口
			add(formDTO.value);
		}
		console.log(formDTO.value);
	};

	/**
	 * 监听分页
	 */
	const handleSizeChange = (val) => {
		query.pageSize = val;
		get()
		console.log(formDTO.value);
	};

	/**
	 * 
	 */
	 const handleCurrentChange = (val) => {
		// query.current = val;
		get()
	// console.log(`current page: ${val}`)
	}

	/**
	 * 选择
	 */
	const handleSelectionChange = (val) => {
		//筛出id列表
		delList.value = val.map((item) => item.userId);
		console.log(val);
	};

	/**
	 * 接口调用------------------------------------------------------------
	 */

	onMounted(() => {
		get()
	})

	const add = (data) => {
		admin.add(formDTO.value).then((res) => {
			ElNotification({
				title: 'Success',
				message: '添加成功',
				type: 'success',
			})
			console.log("获取数据:", res.data)
			get()
		}).catch(err=>{
		ElNotification({
			title: 'Error',
			message: '添加失败',
			type: 'error',
		})
		})
		
	}

	const del = (row) => {
		admin.del(row).then((res) => {
			ElNotification({
				title: 'Success',
				message: '删除成功',
				type: 'success',
			})
			console.log("获取数据:", res.data)
			get()
		}).catch(err=>{
		ElNotification({
			title: 'Error',
			message: '删除失败',
			type: 'error',
		})
		})
		
	}

	const get = () => {
		console.log("查询参数",query.value);
		admin.pageList(query.value).then((res) => {
			formData.value = res.data.data.records
			total.value = res.data.data.total
			// console.log("获取数据:", res.data)
		})
		
	}

	const put = (data) => {
		admin.update(data).then(res=>{
			ElNotification({
				title: 'Success',
				message: '编辑成功',
				type: 'success',
			})
			console.log("修改数据:", res)
			get()
		}).catch(err=>{
		ElNotification({
			title: 'Error',
			message: '编辑失败',
			type: 'error',
		})
		})
	}
</script>

<style scoped>
	.h1 {
		font-size: 25px;
	}
</style>